<?php


namespace App\Modules\Api\Http\Controllers;

use App\Http\Requests\Request;
use App\Models\User;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

/**
 * ChatController
 * created on 2020/11/13 16:05
 * created by chengzhigang
 */
class ChatController extends BaseController
{

    //聊天室登录
    public function login(Request $request){
        try{
            $type = $request->input('type',2);
            switch ($type){
                case 1:
                    return $this->phoneLogin($request);
                    break;
                case 2:
                    return $this->qqLogin($request);
                    break;
                default :
                    return '不支持的登录方式';
                    break;
            }
        }catch(\Exception $e){
            Log::info($e->getMessage());
            Log::info($e->getLine());
            return apiResponse('服务异常');
        }
    }

    //手机登录
    private function phoneLogin($request){
        $phone = $request->input('phone');
        $password = $request->input('password');
        $userInfo = User::where('phone', $phone)->where('status', 1)->first();
        if (empty($userInfo)) {
            return apiResponse('账户不存在');
        }
        //验证密码
        if ($userInfo->password != createUserPwd($password)) {
            return apiResponse('密码不正确');
        }
        //更新用户信息
        if (empty($userInfo->first_login_time)) {
            $userInfo->first_login_time = date('Y-m-d H:i:s');
        }
        $userInfo->login_time = date('Y-m-d H:i:s');
        $userInfo = $userInfo->toArray();
        unset($userInfo['password']);
        $res = User::where('id', $userInfo['id'])->update($userInfo);
        if($res){
            $cookie = $this->setLoginCookie($userInfo);
            $data = [];
            $data['nickname'] = $userInfo['nickname'];
            $data['avatar'] = $userInfo['avatar'];
            $data['remember_user_token'] = $cookie['value'];
            return apiResponse('登录成功',1,$data);
        }else{
            return apiResponse('登录失败');
        }
    }

    //qq登录
    private function qqLogin($request){
        $code = $request->input('code');
        $state = $request->input('state');
        if (!empty($code)) {
            $access_token_url = 'https://graph.qq.com/oauth2.0/token';
            $params = array(
                'client_id'     => config('auth.qq.app_id'),
                'client_secret' => config('auth.qq.app_key'),
                'redirect_uri'  => 'http://app.chengzhigang.cn/api/chat/login',
                'grant_type'    => 'authorization_code',
                'code'          => $code,
                'state'         => $state,
                'type'          => 2
            );
            $result = httpsRequest($access_token_url, $params);
            parse_str($result,$result);
            if ($result&&isset($result['access_token'])) {
                $access_token = $result['access_token'];
                $url = 'https://graph.qq.com/oauth2.0/me?access_token='.$access_token.'&unionid=1';
                $resultData = httpsRequest($url);
                $lpos = strpos($resultData, "(");
                $rpos = strrpos($resultData, ")");
                $resultData = substr($resultData, $lpos+1, $rpos-$lpos-1);
                $resultData = json_decode($resultData,true);
                if($resultData['openid']&&$resultData['unionid']){
                    $url = 'https://graph.qq.com/user/get_user_info?access_token='.$access_token.'&oauth_consumer_key='.config('auth.qq.app_id').'&openid='.$resultData['openid'];
                    $userData = httpsRequest($url);
                    $userData['openId'] = $resultData['openid'];
                    $userData['unionid'] = $resultData['unionid'];
                    $result = $this -> three_login($userData,1);
                    if($result['status']==2){
                        return apiResponse($result['msg']);
                    }else{
                        $cookie = $this->setLoginCookie($result['data']);
                        return redirect()->away(config('auth.qq.redirect_uri').'?'.$cookie['name'].'='.$cookie['value'].'&nickname='.$result['data']['nickname'].'&avatar='.$result['data']['avatar']);
                    }
                }else{
                    return apiResponse('获取unionid失败');
                }
            }
        }else{
            return apiResponse('登录失败');
        }
    }

    //设置用户cookie
    private function setLoginCookie($data){
        //登录成功(设置session)
        $sessionKey = md5(config('const.sign').$data['id']);
        $redis = Redis::connection('auth');
        $redis->set('user_'.$sessionKey,json_encode($data));
        return [
            'name' => 'remember_user_token',
            'value'=> $sessionKey
        ];
    }

    //第三方登录
    private function three_login($data,$type=1){
        $userData = [];
        switch($type){
            case 1:
                $userData['nickname'] = $data['nickname'];
                $userData['openId'] = $data['openId'];
                $userData['unionid'] = $data['unionid'];
                $userData['avatar'] = $data['figureurl'];
                $userData['sex'] = $data['gender']=='男'?1:($data['gender']=='女'?2:3);
                //QQ登录
                break;
            default :
                break;
        }
        if(empty($userData)){
            return ['status'=>2,'msg'=>'未知的登录方式','data'=>[]];
        }else{
            $userData['login_time'] = date('Y-m-d H:i:s');
            $userInfo = User::where('unionid',$userData['unionid'])->select('id')->first();
            if(empty($userInfo)){
                $userData['first_login_time'] = date('Y-m-d H:i:s');
                $res = User::create($userData);
                $userData['id'] = $res->id;
            }else{
                $userData['id'] = $userInfo->id;
                $res = $userInfo->update($userData);
            }
            if($res){
                return ['status'=>1,'msg'=>'登录成功','data'=>$userData];
            }else{
                return ['status'=>2,'msg'=>'登录失败','data'=>[]];
            }
        }
    }

}